package net.sikorscy.lampmanager;

import net.sikorscy.lampmanager.comapi.ComApi;
import net.sikorscy.lampmanager.comapi.ComException;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.dialogs.ListDialog;


public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

	private void initCom(Shell shell) {
		final IWorkbench workbench = PlatformUI.getWorkbench();
		String comPort = null;
		ListDialog ld = new ListDialog(shell);
		ld.setAddCancelButton(true);
		ld.setContentProvider(new ArrayContentProvider());
		ld.setLabelProvider(new LabelProvider());
		ld.setInput(ComApi.getComPorts().toArray());
		ld.setTitle("Select COM port :");
		ld.open();
		comPort = (String) ((ld.getResult() == null || ld.getResult().length < 1) ? null
				: ld.getResult()[0]);
		if (comPort == null) {
			MessageDialog.openError(shell, "No COM port selected",
					"No COM port selected");
			workbench.close();
			System.exit(1);
		}
		Application.setComApi(new ComApi());
		try {
			Application.getComApi().init(comPort);
		} catch (ComException e) {
			MessageDialog.openError(shell, "Comunication errror", e
					.getMessage());
			workbench.close();
			System.exit(1);
		}
	}

	public ApplicationWorkbenchWindowAdvisor(
			IWorkbenchWindowConfigurer configurer) {
		super(configurer);
	}

	public ActionBarAdvisor createActionBarAdvisor(
			IActionBarConfigurer configurer) {
		return new ApplicationActionBarAdvisor(configurer);
	}

	public void preWindowOpen() {
		IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
		configurer.setInitialSize(new Point(700, 600));
		configurer.setShowCoolBar(false);
		configurer.setShowStatusLine(false);
		configurer.setTitle("AquaCTL");
		initCom(Display.getCurrent().getActiveShell());
	}
}
